package fcnet

import (
	"errors"
	"sync"

	"gitee.com/fcsvr/fancy/fclog"
)

type ConnMgr struct {
	conns map[uint32]*Conn
	lock  sync.RWMutex
}

func NewConnMgr() *ConnMgr {
	return &ConnMgr{
		conns: make(map[uint32]*Conn),
	}
}

func (this *ConnMgr) Add(conn *Conn) {
	this.lock.Lock()
	defer this.lock.Unlock()

	this.conns[conn.GetConnID()] = conn
	fclog.Info("ConnMgr Add: add id = %d, all conns num = %d", conn.GetConnID(), this.Len())
}

func (this *ConnMgr) Remove(conn *Conn) {
	this.lock.Lock()
	defer this.lock.Unlock()

	delete(this.conns, conn.GetConnID())
	fclog.Info("ConnMgr Remove: remove id = %d, all conns num = %d", conn.GetConnID(), this.Len())
}

func (this *ConnMgr) Get(connid uint32) (*Conn, error) {
	this.lock.Lock()
	defer this.lock.Unlock()

	if conn, ok := this.conns[connid]; ok {
		return conn, nil
	} else {
		return nil, errors.New("connection not found")
	}
}

func (this *ConnMgr) Len() int {
	return len(this.conns)
}

func (this *ConnMgr) ClearConn() {
	this.lock.Lock()
	defer this.lock.Unlock()

	for connid, conn := range this.conns {
		conn.SvrStop()
		delete(this.conns, connid)
	}

	fclog.Info("ConnMgr ClearConn: successful, all conns num = %d", this.Len())
}
